package com.dbxt.teacher.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.HashMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dbxt.entity.Clerk;
import com.dbxt.entity.ClerkRecord;
import com.dbxt.entity.Files;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dbxt.entity.Record;
import com.dbxt.entity.RecordTeacher;
import com.dbxt.entity.Student;
import com.dbxt.entity.Teacher;
import com.dbxt.teacher.service.TeacherService;
import com.dbxt.teacher.service.impl.TeacherServiceImpl;
import com.dbxt.util.AsposeWord;
import com.dbxt.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/teacher")
public class TeacherController {
	@Autowired
	private TeacherService impl;

	//查找学生个人基本信息
	@RequestMapping(value="/selectOneStudent",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject selectOneStudent(Integer sid,HttpSession session,Integer tid,Integer rtid){
		JSONObject json = new JSONObject();
		int status=-1;			
			Student selectRecordByStudent = impl.selectRecordByStudent(sid);
			Teacher teacher = impl.selectTeacher(tid);
			RecordTeacher record=impl.selectRtid(rtid);				
			if (record.getTeacher()== null||record.getTeacher().equals("")){
				record.setTeacher(teacher);
				if (impl.updateRtid(record)) {				
					RecordTeacher recordTeacher = impl.selectRecordTeacherByTeacher(tid,selectRecordByStudent.getRecord().getRid());			
					if (selectRecordByStudent != null) {
						status=0;
						session.setAttribute("studentBySid", selectRecordByStudent);
						json.put("recordTeacher", recordTeacher);
						json.put("student", selectRecordByStudent);				
					}
				}								
			}
			else {
				RecordTeacher recordTeacher = impl.selectRecordTeacherByTeacher(tid,selectRecordByStudent.getRecord().getRid());			
				if (selectRecordByStudent != null) {
					status=1;
					session.setAttribute("studentBySid", selectRecordByStudent);
					json.put("recordTeacher", recordTeacher);
					json.put("student", selectRecordByStudent);				
				}
			}
									
			
			json.put("status", status);
		return json;
	}
	/**
	 * 书记员查个人信息
	 * @param sid
	 * @param session
	 * @param cid
	 * @return
	 */
	@RequestMapping(value="/selectOneStudentByClerk",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject selectOneStudentByClerk(Integer sid,HttpSession session,Integer cid,Integer crid){
		JSONObject json = new JSONObject();
		int status=-1;			
			Student selectRecordByStudent = impl.selectRecordByStudent(sid);
			Clerk selectClerk = impl.selectClerk(cid);
			ClerkRecord clerkRecord=impl.selectCrid(crid);				
			if (clerkRecord.getClerk()==null||clerkRecord.getClerk().equals("")) {
				clerkRecord.setClerk(selectClerk);
				if (impl.updateCrid(clerkRecord)) {
					ClerkRecord selectClerkRecordByClerk = impl.selectClerkRecordByClerk(cid,selectRecordByStudent.getRecord().getRid());					
					if (selectRecordByStudent != null) {
						status=0;			
						session.setAttribute("studentBySid", selectRecordByStudent);
						json.put("ClerkRecord", selectClerkRecordByClerk);
						json.put("student", selectRecordByStudent);				
					}
				}								
			}
			else {
				ClerkRecord selectClerkRecordByClerk = impl.selectClerkRecordByClerk(cid,selectRecordByStudent.getRecord().getRid());								
				if (selectRecordByStudent != null) {
					status=1;
					session.setAttribute("studentBySid", selectRecordByStudent);
					json.put("ClerkRecord", selectClerkRecordByClerk);
					json.put("student", selectRecordByStudent);				
				}
			}			
			json.put("status", status);
		return json;
	}
	
	@RequestMapping(value="/updateStatusByRecord",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject updateStatusByRecord(HttpSession session,String recordStatus){
		JSONObject json = new JSONObject();
		int status=-1;
		Teacher teacher= (Teacher) session.getAttribute("teacher");	
		Student student = (Student) session.getAttribute("studentBySid");
		Record record = impl.selectRecordByStudentUpdate(student.getRecord().getRid());
		record.setStatus(recordStatus);			
		boolean b = impl.updateRecordByTeacher(record);
		if (b) {
			status=0;
			json.put("message", "修改答辩状态成功");
			json.put("record", record);
		}
		json.put("status", status);
		return json;
		
	}
	//老师修改分数与评语
	@RequestMapping(value="/updateScoreAndCommitByTeacher",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject updateScoreAndCommitByTeacher(HttpSession session,String comment,Integer score){
		JSONObject json = new JSONObject();
		int status=-1;
		Teacher teacher= (Teacher) session.getAttribute("teacher");	
		Student student = (Student) session.getAttribute("studentBySid");
		
		RecordTeacher recordTeacher = impl.selectRecordTeacherByTeacher(teacher.getTid(),student.getRecord().getRid());	
		
		if (recordTeacher != null && !recordTeacher.equals("")) {
			recordTeacher.setScore(score);	
			recordTeacher.setComment(comment);
			boolean update = impl.updateScoreAndCommitByTeacher(recordTeacher);					
			if (update){							
				json.put("message", "修改分数和评语成功");
				json.put("recordTeacher", recordTeacher);
				json.put("status", 0);
			}							
		}
		else {
			recordTeacher=new RecordTeacher();
			recordTeacher.setComment(comment);
			recordTeacher.setTeacher(teacher);
			recordTeacher.setScore(score);
			recordTeacher.setRecord(student.getRecord());
			boolean a = impl.insertRecordTeacher(recordTeacher);		
			if (a){	
				json.put("message", "添加分数和评语成功");
				json.put("recordTeacher", recordTeacher);
				json.put("status", 0);
			}	
			
		}				
		return json;		
	}
//	@RequestMapping(value="selectStudentList",method=RequestMethod.POST)
//	@ResponseBody
//	public JSONObject selectStudentList(Integer pageNum,Integer pageSize){
//		JSONObject json = new JSONObject();
//		PageHelper.startPage(pageNum, pageSize);
////		List<Student> studentList = impl.selectStudentList(pageSize);
////		PageInfo<Student> pageInfo=new PageInfo<Student>(studentList);
//	
//		json.put("pageInfo", pageInfo);
//		return json;		
//	}
//获取答辩成绩	
	@RequestMapping(value="/selectCountTeacher",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject selectCountTeacher(HttpSession session,Integer sid){
		JSONObject json = new JSONObject();
		int status=-1;
		Student student = (Student) session.getAttribute("student");
		if(student!=null){
			Student student2 = impl.selectRecordByStudent(student.getSid());//通过student查询record											
				int countTeacher = impl.selectCountTeacher(student2.getRecord().getRid());//获取record id对应的teacher id	进行计数		
				if (countTeacher==3) {
					List<RecordTeacher> RT = impl.selectCountGradeByTeacher(student2.getRecord().getRid());//根据rid 获取到中间表对应的score 
					double sum=(double) RT.stream().collect(Collectors.summingInt(RecordTeacher::getScore));//计算分数总数
					double a=sum/countTeacher;										
					int avg=(int) Math.round(a);
					Record record=student2.getRecord();
					record.setGrade(avg);
					record.setStatus("1");
					try {
						record.setTimes(DateUtil.getCurrentDateTime());
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					boolean b = impl.updateRecordGrade(record);//修改record表中的平均分
					if (b) {
						json.put("message", "当前已经有"+countTeacher+"位老师为你打分");
						json.put("grade", record.getGrade());
						json.put("times", record.getTimes());
						status=2;
					}				
				}
				else {
					Record record=student2.getRecord();
					record.setGrade(null);
					boolean b = impl.updateRecordGrade(record);
					if (b) {
						json.put("message", "当前已经有"+countTeacher+"为你打分");
						json.put("message2", "未达三位老师打分，总分数为null");
						json.put("grade", record.getGrade());
						status=0;
					}								
				}				
				json.put("countTeacher", countTeacher);			
		
		}
		//老师查看学生答辩成绩
		else {
					Student studentByTeacher = impl.selectRecordByStudent(sid);							
					int countTeacher = impl.selectCountTeacher(studentByTeacher.getRecord().getRid());//获取record id对应的teacher id	进行计数		
					if (countTeacher>0) {
						List<RecordTeacher> RT = impl.selectCountGradeByTeacher(studentByTeacher.getRecord().getRid());//根据rid 获取到中间表对应的score 
						double sum=(double) RT.stream().collect(Collectors.summingInt(RecordTeacher::getScore));//计算分数总数						
						int avg=(int) Math.round(sum/countTeacher);
						Record record=studentByTeacher.getRecord();
						record.setGrade(avg);
						record.setStatus("1");
						boolean b = impl.updateRecordGrade(record);//修改record表中的平均分
						if (b) {
							json.put("message", "当前已经有"+countTeacher+"位老师为你打分");
							json.put("grade", record.getGrade());
							status=2;
						}				
					}
					else {
						Record record=studentByTeacher.getRecord();
						record.setGrade(null);
						boolean b = impl.updateRecordGrade(record);
						if (b) {
							json.put("message", "当前已经有"+countTeacher+"为你打分");
							json.put("grade", record.getGrade());
							status=0;
						}								
					}				
					json.put("countTeacher", countTeacher);	
				 
			
		}
		json.put("status", status);
		return json;
				
	}
		
	@RequestMapping(value="/updataStatus",method=RequestMethod.GET)
	@ResponseBody
	public Map<String , Object> updataStatus(Integer sid ,HttpServletRequest request){
		Map<String ,Object> map = new HashMap<>();
		Student student = new Student();
		Record record = new Record();
		student.setSid(sid);
		record.setStudent(student);
		if (impl.UpdataRecord(record)) {
			map.put("status", 0);
			return map;
			
		}else {
			map.put("status", 1);
		}
		return map;
	}
	@RequestMapping(value="showContent",method=RequestMethod.POST)
	@ResponseBody
	public JSONObject showContent(HttpSession session,Integer fid,HttpServletRequest request) throws Exception{
		JSONObject json = new JSONObject();
		int status=-1;
		 Files filea = impl.selectFile(fid);
		 String substring = filea.getName().substring(12, 15);
		 System.out.println(substring);
		 if (substring.equals("论文.")) {
			 if (filea.getName().endsWith(".doc")) {		
				 status=1;
				 json.put("doc", new AsposeWord().parseWord2Html(filea.getName(),request));
				 json.put("message", "当前doc格式的论文");
			}else if (filea.getName().endsWith(".docx")) {
				status=2;			
				json.put("docx", new AsposeWord().parseWord2Html(filea.getName(),request));	
				json.put("message", "当前docx格式的论文");				
			}
			else if (filea.getName().endsWith(".pdf")) {
				 status=3;
				 json.put("pdf", filea.getName());
//				 json.put("doc", new AsposeWord().parsePDF2Html(filea.getName(),request));
				 json.put("message", "当前pdf格式的论文");
			}
			else {
				json.put("message", "当前不是word或pdf的论文");
			}		
		}
		 else if (substring.equals("任务书")) {
			 if (filea.getName().endsWith(".doc")) {		
				 status=4;
				 json.put("doc", new AsposeWord().parseWord2Html2(filea.getName(),request));
				 json.put("message", "当前doc格式的任务书");
			}else if (filea.getName().endsWith(".docx")) {
				status=5;			
				json.put("docx", new AsposeWord().parseWord2Html2(filea.getName(),request));	
				json.put("message", "当前docx格式的任务书");
			}
			else if (filea.getName().endsWith(".pdf")) {
				 status=6;
				 json.put("pdf", filea.getName());
//				 json.put("doc", new AsposeWord().parsePDF2Html2(filea.getName(),request));
				 json.put("message", "当前pdf格式的任务书");
			}else {
				json.put("message", "当前不是word或pdf的任务书");
			}		
		} 
		else {
			json.put("message", "当前命名格式不正确");
		} 
		json.put("status", status);
		return json;		
	}	
//	@RequestMapping(value="selectTeacherGrouping",method=RequestMethod.POST)
//	@ResponseBody
//	public JSONObject selectTeacherGrouping(HttpSession session){
//		JSONObject json = new JSONObject();
//		int status=-1;
//		Teacher teacher = (Teacher) session.getAttribute("teacher");
//		
//		List<Student> selectStudentList = impl.selectStudentList(teacher.getGrouping(),teacher.getTid());
		
//		for(Student student:selectStudentList){
//			if (student.getRecord().getRecordTeachers().equals("")) {
//				RecordTeacher recordTeacher=new RecordTeacher();
//				recordTeacher.setComment(null);
//				recordTeacher.setTeacher(teacher);
//				recordTeacher.setScore(null);
//				recordTeacher.setRecord(student.getRecord());
//				boolean a = impl.insertRecordTeacher(recordTeacher);
//				if (a) {
//					status=2;
//					json.put("recordTeacher", recordTeacher);
//					json.put("message", "添加了recordTeacher数据成功,设定初始为null");
//				}
//				else {
//					status=1;					
//					json.put("message", "失败");
//				}
//			}
//			else {
//				json.put("message", "当前已有recordTeacher");
//			}
//		}
//		
//		if (selectStudentList.size()==0) {		
//			status=0;
//			json.put("message", "未评分");			
//		}
//		else {
//			status=1;
//			json.put("message", "操作成功");		
////		}
//		json.put("status", status);
//		json.put("list", selectStudentList);
//		return json;
//		
//	}
	@RequestMapping(value = "/checkResult", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject checkResult(Integer sid){
		JSONObject json = new JSONObject();
		int status=-1;
		if (sid==null) {	
			status=0;
			json.put("message", "传值为NULL");				
		}else {
			status=1;
			Student checkResult = impl.checkResult(sid);
			if (checkResult==null) {
				json.put("message", "找不到改学生");	
			}
			json.put("student", checkResult);
		}
		
		json.put("status", status);	
		return null;
		
	}
}

